package com.supor.aiot.food.ui.food;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alipay.mobile.common.utils.StringUtils;
import com.android.baseconfig.base.BaseActivity;
import com.android.baseconfig.base.BasePresenter;
import com.android.baseconfig.base.BaseSharedPreferences;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ToastUtils;
import com.android.baseconfig.common.views.ClearEditText;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.app.api.DeviceImpl;
import com.supor.aiot.common.arouter.PathUrl;
import com.supor.aiot.common.entity.ProductType;
import com.supor.aiot.food.R;
import com.supor.aiot.food.adapter.RecipeHotAdapter;
import com.supor.aiot.food.api.SearchFoodImpl;
import com.supor.aiot.food.bean.BindDeviceBean;
import com.supor.aiot.food.bean.RecipeHotBean;
import com.supor.aiot.food.bean.RecipeStoreBean;
import com.supor.aiot.food.ormlite.Cache;
import com.supor.aiot.food.view.GrideDecoration;
import com.supor.aiot.food.view.SelectDevicePopwindow;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import butterknife.ButterKnife;

public class SearchResultActivity extends BaseActivity implements TextView.OnEditorActionListener {

    private SwipeRecyclerView rvRecipeDetail;
    private LinearLayout llRecipeNone;
    private ImageView ivSelectedState;
    //    private LinearLayout llResultOuter;
    private TextView tvResultSum;
    private TextView tvSelectDevice;
    private ImageView ivResultBack;
    private ClearEditText edtSearch;
    private String keyword;
    private String defaultWord;
    //    private RelativeLayout rlResultNone;
    private SmartRefreshLayout refreshLayout;
    private List<RecipeHotBean> mHotList = new ArrayList<>();
    private List<Cache> cacheList = new ArrayList<>();
    private List<String> mList;
    private String historyInput;
    private RecipeHotAdapter hotAdapter;
    private Long lastSearchTime;
    private static final String SEARCH_KEYWORD = "SEARCH_KEYWORD";
    private static final String SEARCH_DEFAULT = "SEARCH_DEFAULT";
    private static final String CHEF_ID = "CHEF_ID";
    private int originPage = 1;
    private SelectDevicePopwindow selectDevicePopwindow;
    private List<BindDeviceBean> mDeviceList = new ArrayList<>();
    private int dPosition;
    private String productModel = "";
    private String deviceName;

    @Override
    protected int resourceId() {
        return R.layout.activity_search_result;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(resourceId());
        ButterKnife.bind(this);
        initView();
        initListener();
        initClassifyData();
        initRecycleView();
    }

    @SuppressLint("AutoDispose")
    private void getAllDevices() {
        DeviceImpl.getInstance().getAllDevice(1000).subscribe(result -> {
            mDeviceList.clear();
            List<ProductType> productTypeList = result.data.rows;
            int position = 0;
            for (ProductType productType : productTypeList) {
                for (ProductType.ProductModel child : productType.Children) {
                    BindDeviceBean bindDeviceBean = new BindDeviceBean();
                    bindDeviceBean.setModelId(child.modelId);
                    bindDeviceBean.setModelTypeName(child.crmModelName);
                    bindDeviceBean.setRemark(child.remark);
                    bindDeviceBean.setParentTypeImage(child.modelPicture);
                    bindDeviceBean.setBind(child.bindStatus);
                    mDeviceList.add(bindDeviceBean);
                    if (!TextUtils.isEmpty(deviceName) && deviceName.equals(child.crmModelName)) {
                        position = mDeviceList.size();
                    }
                }
            }
            setPopChoicePosition(position);
        }, throwable -> {
            Logc.e("accept: " + throwable);
            // ToastUtils.getInstance().showCustomToast("获取产品失败");
        });
    }

    private void initListener() {
        ivResultBack.setOnClickListener(view -> {
            hintKeyboard();
            SearchResultActivity.this.finish();
        });
        edtSearch.setOnEditorActionListener(this);
//        rlResultNone.setOnClickListener(view -> {
//        if (!AppAgent.isLogin()) {
//            AppAgent.showLogin(true);
//            ARouter.getInstance().build(PathUrl.PATH_LOGIN)
//                    .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
//                            com.android.baseconfig.R.anim.activity_open_exit)
//                    .navigation(SearchResultActivity.this);
//
//        }else {
//            ARouter.getInstance().build(PathUrl.PATH_ADD_IPS)
//                    .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
//                            com.android.baseconfig.R.anim.activity_open_exit)
//                    .navigation(SearchResultActivity.this);
//        }
//        });
    }


    //关闭软键盘 可以在finish之前调用一下
    private void hintKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && getCurrentFocus() != null) {
            if (getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    //点击软键盘确定
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        int id = v.getId();
        if (id == R.id.edt_common_search) {

            if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                initCacheData();
                if (lastSearchTime != null) {
                    long temp = System.currentTimeMillis() - lastSearchTime;
                    if (temp < 1000) {
                        return true;
                    }
                }
                lastSearchTime = System.currentTimeMillis();

                String keywords = edtSearch.getText().toString().trim();
                keyword = keywords;
                originPage = 1;
                searchRecipe(productModel, keywords);
                //insert data
                boolean contains = false;
                for (int i = 0; i < cacheList.size(); i++) {
                    if (keywords.equals(cacheList.get(i).getCache())) {
                        contains = true;
                    }
                }
                if (!contains) {
                    Cache cache = new Cache(keywords);
                    cacheList.add(cache);
                    List<String> temp = new ArrayList<>();
                    for (int i = 0; i < cacheList.size(); i++) {
                        temp.add(cacheList.get(i).getCache());
                    }
                    String export = listToString(temp);
                    BaseSharedPreferences.setString(SearchResultActivity.this, Constants.Key.SEARCH_HISTORY, export);
                }

                return true;
            }
        }
        return false;
    }

    @Override
    protected void initView() {
        super.initView();
        getAllDevices();
        rvRecipeDetail = findViewById(R.id.rl_search_result);
        llRecipeNone = findViewById(R.id.ll_search_empty);
//        llResultOuter = findViewById(R.id.ll_result_outer);
        ivSelectedState = findViewById(R.id.iv_selected_state);
        tvResultSum = findViewById(R.id.tv_result_sum);
        tvSelectDevice = findViewById(R.id.tv_selected_device);

        ivResultBack = findViewById(R.id.iv_back);
        edtSearch = findViewById(R.id.edt_common_search);
//        rlResultNone = findViewById(R.id.rl_add_ips);
        refreshLayout = findViewById(R.id.refreshLayout);
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setRefreshFooter(new ClassicsFooter(SearchResultActivity.this));
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            originPage++;
            searchRecipe(productModel, keyword);
        });
        initChoiceDevice();
        findViewById(R.id.rl_select_device).setOnClickListener(view -> {
            selectDevicePopwindow = new SelectDevicePopwindow(this);
            selectDevicePopwindow.setDeviceData(mDeviceList);
            // 设置PopupWindow的背景
            selectDevicePopwindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            // 设置PopupWindow是否能响应外部点击事件
            selectDevicePopwindow.setOutsideTouchable(true);
            // 设置PopupWindow是否能响应点击事件
            selectDevicePopwindow.setTouchable(true);
            selectDevicePopwindow.showAsDropDown(findViewById(R.id.rl_select_device), 0, -30);
            selectDevicePopwindow.setPopDevicePosition(dPosition);
            selectDevicePopwindow.setPopDeviceListener((position, typeID, deviceType) -> {
//                if (!TextUtils.isEmpty(deviceType))
//                    tvSelectDevice.setText(deviceType);
//                productModel = typeID;
//                String keywords = edtSearch.getText().toString().trim();
//                keyword = keywords;
//                originPage = 1;
//                searchRecipe(productModel, keywords);
//                dPosition = position;
//                selectDevicePopwindow.setPopDevicePosition(dPosition);
                popChoice(position, typeID, deviceType);
            });
            ivSelectedState.setImageResource(R.mipmap.ic_black_up);
            selectDevicePopwindow.setOnDismissListener(() -> {
                ivSelectedState.setImageResource(R.mipmap.ic_black_down);
            });
        });
    }

    private void initChoiceDevice() {
        if (null != getIntent()) {
            productModel = getIntent().getStringExtra("DEVICE_RECIPE");
            deviceName = getIntent().getStringExtra("DEVICE_RECIPE_NAME");
        }
        if (!TextUtils.isEmpty(deviceName)) {
            tvSelectDevice.setText(deviceName);
        }
    }

    private void popChoice(int position, String typeID, String deviceType) {
        if (!TextUtils.isEmpty(deviceType))
            tvSelectDevice.setText(deviceType);
        productModel = typeID;
        String keywords = edtSearch.getText().toString().trim();
        keyword = keywords;
        originPage = 1;
        searchRecipe(productModel, keywords);
        setPopChoicePosition(position);
    }

    private void setPopChoicePosition(int position) {
        dPosition = position;
        selectDevicePopwindow.setPopDevicePosition(dPosition);
    }


    @SuppressLint("AutoDispose")
    private void searchRecipe(String productModel, String keyword) {
        SearchFoodImpl.getInstance().searchRecipe(productModel, keyword, originPage, 10).subscribe(result -> {
            if (result.isSuccess()) {
                hintKeyboard();
                if (result.data.rows.size() > 0) {
                    if (originPage == 1) mHotList.clear();
                    if (mHotList.size() < result.total) {
                        mHotList.addAll(result.data.rows);
                    } else {
                        View footerView = getLayoutInflater().inflate(R.layout.item_nomore, rvRecipeDetail, false);
                        if (mHotList.size() > 0 && rvRecipeDetail.getFooterCount() == 0)
                            rvRecipeDetail.addFooterView(footerView);
                    }
                    if (originPage == 1) {
                        tvResultSum.setText(getResources().getString(R.string.search_total) + result.data.getTotal() + getResources().getString(R.string.search_recipes));
//                        llResultOuter.setVisibility(View.VISIBLE);
                        llRecipeNone.setVisibility(View.GONE);
                        refreshLayout.setVisibility(View.VISIBLE);
                    }
                    hotAdapter.notifyDataSetChanged();
                } else {
                    llRecipeNone.setVisibility(View.VISIBLE);
//                    llResultOuter.setVisibility(View.GONE);
                    tvResultSum.setText(getResources().getString(R.string.search_total) + 0 + getResources().getString(R.string.search_recipes));
                    refreshLayout.setVisibility(View.GONE);
                }

            } else {
                Log.e(TAG, "rsult error");
                hintKeyboard();
            }
            refreshLayout.finishLoadMore();
        }, throwable -> {
            Log.e(TAG, "查询失败: " + throwable.getMessage());
            hintKeyboard();
            refreshLayout.finishLoadMore();
        });
    }


    /**
     * 收藏食谱
     *
     * @param storeBean
     */
    @SuppressLint("AutoDispose")
    private void setRecipeStored(RecipeStoreBean storeBean) {
        SearchFoodImpl.getInstance().recipeStore(storeBean).subscribe(result -> {
            if (result.isSuccess()) {
                originPage = 1;
                searchRecipe(productModel, keyword);
            } else {
                Log.e(TAG, "foodRecommond error");
            }

        }, throwable -> {
            Log.e(TAG, "foodRecommond查询失败: " + throwable.getMessage());
        });
    }

    /**
     * 取消收藏食谱
     *
     * @param favoriteId
     */
    @SuppressLint("AutoDispose")
    private void cancelRecipeStored(int favoriteId) {
        SearchFoodImpl.getInstance().cancleRecipeStore(favoriteId).subscribe(result -> {
            if (result.isSuccess()) {
                originPage = 1;
                searchRecipe(productModel, keyword);
            } else {
                Log.e(TAG, "foodRecommond error");
            }

        }, throwable -> {
            Log.e(TAG, "foodRecommond查询失败: " + throwable.getMessage());
        });
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initRecycleView() {
        hotAdapter = new RecipeHotAdapter(mHotList, SearchResultActivity.this);
        hotAdapter.setShowName(true);
        hotAdapter.setRecipeHotListener(new RecipeHotAdapter.OnClassifyClickListener() {
            @Override
            public void OnItemClick(int position) {
                RecipeHotBean bean = mHotList.get(position);
                AppAgent.startRecipePage(bean.getRecipeId(), bean.getModelId());
            }

            @Override
            public void OnItemLongClick(int position) {

            }

            @Override
            public void OnAvatarClick(int position) {
                RecipeHotBean hotBean = mHotList.get(position);
                if (!TextUtils.isEmpty(hotBean.getChefId())) {
                    Intent intent = new Intent(SearchResultActivity.this, CookerHomeActivity.class);
                    intent.putExtra(CHEF_ID, hotBean.getChefId());
                    startActivity(intent);
                } else {
                    ToastUtils.getInstance().showCustomToast(R.string.check_error);
                }
            }

            @Override
            public void OnStarClick(int position) {
                RecipeHotBean bean = mHotList.get(position);
                int state = bean.getFavoriteType();
                if (AppAgent.isLogin()) {
                    if (state == 1) {
                        Log.e(TAG, "cancleStore");
                        cancelRecipeStored(bean.getFavoriteId());
                    } else {
                        RecipeStoreBean storeBean = new RecipeStoreBean();
                        storeBean.setAddrId(bean.getRecipeId());
                        storeBean.setFavoriteAddr("RECIPE_ID");
                        setRecipeStored(storeBean);
                    }
                } else {
                    SuporPresenter.getInstance().getCmccHelper().displayLogin(true);
                }
            }

            @Override
            public void OnUnlikeRecipe(int position) {

            }

            @Override
            public void OnUnlikeClassify(int position) {

            }
        });
        rvRecipeDetail.setAdapter(hotAdapter);
        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        rvRecipeDetail.setLayoutManager(staggeredGridLayoutManager);
        rvRecipeDetail.addItemDecoration(new GrideDecoration(SearchResultActivity.this));
    }

    private void initClassifyData() {
        keyword = getIntent().getStringExtra(SEARCH_KEYWORD);
        defaultWord = getIntent().getStringExtra(SEARCH_DEFAULT);
        if (!TextUtils.isEmpty(keyword)) {
            edtSearch.setText(keyword);
            searchRecipe(productModel, keyword);
        } else {
            llRecipeNone.setVisibility(View.VISIBLE);
//            llResultOuter.setVisibility(View.GONE);
            tvResultSum.setText("");
            refreshLayout.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(defaultWord)) {
            edtSearch.setHint(defaultWord);
        } else {
            edtSearch.setHint(getResources().getString(R.string.default_recomond));
        }
    }

    private void initCacheData() {
        historyInput = BaseSharedPreferences.getString(SearchResultActivity.this, Constants.Key.SEARCH_HISTORY);
        mList = stringToList(historyInput);
        cacheList.clear();
        if (mList != null && mList.size() > 0) {
            for (int i = 0; i < mList.size(); i++) {
                Cache cache = new Cache(i, mList.get(i));
                cacheList.add(cache);
            }
        }
    }

    public String listToString(List list) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            if (i == list.size() - 1) {
                sb.append(list.get(i));
            } else {
                sb.append(list.get(i));
                sb.append(",");
            }
        }
        return sb.toString();
    }

    private List<String> stringToList(String strs) {
        if (!StringUtils.isEmpty(strs)) {
            String str[] = strs.split(",");
            return Arrays.asList(str);
        } else {
            return new ArrayList<>();
        }
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }
}

